package org.ladybug.service.auth;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.skins.io.HexReader;
import org.springframework.dao.DataAccessException;
import org.springframework.security.providers.encoding.PasswordEncoder;

public class LadybugPasswordEncoder implements PasswordEncoder {

	public String encodePassword(String rawPass, Object salt)
			throws DataAccessException {
		System.out.println("LadybugPasswordEncoder.encodePassword()");
		System.out.println("Salt: "+salt);
		System.out.println("Pass: "+rawPass);
		byte[] keyPassword = "sssssssssssssssssssssssssssss".getBytes();
		try {
			keyPassword = new
			 StringBuffer(salt.toString()).append(rawPass).toString().getBytes();
			 keyPassword = MessageDigest.getInstance("SHA").digest(keyPassword);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}

		return HexReader.bytesToHex(keyPassword);
	}

	public boolean isPasswordValid(String encPass, String rawPass, Object salt)
			throws DataAccessException {
		
		System.out.println("LadybugPasswordEncoder.isPasswordValid()");
		System.out.println("EncPass: "+encPass);
		System.out.println("rawPass: "+rawPass);
		System.out.println("salt: "+salt);
		boolean result = encPass.equals(encodePassword(rawPass, salt));
		System.out.println("Result: "+result);
		return result;
	}

}
